package com.magicsoft.share.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.util.Base64;
import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

/**
 * Created by lyf on 2017/12/22/022.
 */

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//


public class FileTool {
    public static final int BUFSIZE = 8192;
    private static final String TAG = "RxFileTool";

    public FileTool() {
    }

    public static File getRootPath() {
        File path = null;
        if(sdCardIsAvailable()) {
            path = Environment.getExternalStorageDirectory();
        } else {
            path = Environment.getDataDirectory();
        }

        return path;
    }

    public static File getCecheFolder(Context context) {
        File folder = new File(context.getCacheDir(), "IMAGECACHE");
        if(!folder.exists()) {
            folder.mkdir();
        }

        return folder;
    }

    public static boolean isSDCardEnable() {
        return "mounted".equals(Environment.getExternalStorageState());
    }

    public static String getSDCardPath() {
        return !isSDCardEnable()?"sdcard unable!":Environment.getExternalStorageDirectory().getPath() + File.separator;
    }

    public static String getDataPath() {
        return !isSDCardEnable()?"sdcard unable!":Environment.getDataDirectory().getPath();
    }



    public static boolean sdCardIsAvailable() {
        if(Environment.getExternalStorageState().equals("mounted")) {
            File sd = new File(Environment.getExternalStorageDirectory().getPath());
            return sd.canWrite();
        } else {
            return false;
        }
    }


    public static boolean renameFile(String resFilePath, String newFilePath) {
        File resFile = new File(resFilePath);
        File newFile = new File(newFilePath);
        return resFile.renameTo(newFile);
    }

    @SuppressLint({"NewApi"})
    public static long getSDCardAvailaleSize() {
        File path = getRootPath();
        StatFs stat = new StatFs(path.getPath());
        long blockSize;
        long availableBlocks;
        if(Build.VERSION.SDK_INT >= 18) {
            blockSize = stat.getBlockSizeLong();
            availableBlocks = stat.getAvailableBlocksLong();
        } else {
            blockSize = (long)stat.getBlockSize();
            availableBlocks = (long)stat.getAvailableBlocks();
        }

        return availableBlocks * blockSize;
    }

    @SuppressLint({"NewApi"})
    public static long getDirSize(String path) {
        StatFs stat = new StatFs(path);
        long blockSize;
        long availableBlocks;
        if(Build.VERSION.SDK_INT >= 18) {
            blockSize = stat.getBlockSizeLong();
            availableBlocks = stat.getAvailableBlocksLong();
        } else {
            blockSize = (long)stat.getBlockSize();
            availableBlocks = (long)stat.getAvailableBlocks();
        }

        return availableBlocks * blockSize;
    }

    public static long getFileAllSize(String path) {
        File file = new File(path);
        if(!file.exists()) {
            return 0L;
        } else if(!file.isDirectory()) {
            return file.length();
        } else {
            File[] childrens = file.listFiles();
            long size = 0L;
            File[] var5 = childrens;
            int var6 = childrens.length;

            for(int var7 = 0; var7 < var6; ++var7) {
                File f = var5[var7];
                size += getFileAllSize(f.getPath());
            }

            return size;
        }
    }

    public static boolean initFile(String path) {
        boolean result = false;

        try {
            File e = new File(path);
            if(!e.exists()) {
                result = e.createNewFile();
            } else if(e.isDirectory()) {
                e.delete();
                result = e.createNewFile();
            } else if(e.exists()) {
                result = true;
            }
        } catch (IOException var3) {
            var3.printStackTrace();
        }

        return result;
    }

    public static boolean initDirectory(String path) {
        boolean result = false;
        File file = new File(path);
        if(!file.exists()) {
            result = file.mkdir();
        } else if(!file.isDirectory()) {
            file.delete();
            result = file.mkdir();
        } else if(file.exists()) {
            result = true;
        }

        return result;
    }

    public static void copyFile(File from, File to) throws IOException {
        if(!from.exists()) {
            throw new IOException("The source file not exist: " + from.getAbsolutePath());
        } else {
            FileInputStream fis = new FileInputStream(from);

            try {
                copyFile((InputStream)fis, (File)to);
            } finally {
                fis.close();
            }

        }
    }

    public static long copyFile(InputStream from, File to) throws IOException {
        long totalBytes = 0L;
        FileOutputStream fos = new FileOutputStream(to, false);

        try {
            int len;
            for(byte[] data = new byte[1024]; (len = from.read(data)) > -1; totalBytes += (long)len) {
                fos.write(data, 0, len);
            }

            fos.flush();
            return totalBytes;
        } finally {
            fos.close();
        }
    }

    public static void saveFile(InputStream inputStream, String filePath) {
        try {
            FileOutputStream e = new FileOutputStream(new File(filePath), false);
            byte[] buffer = new byte[1024];

            int len;
            while((len = inputStream.read(buffer)) != -1) {
                e.write(buffer, 0, len);
            }

            e.flush();
            e.close();
        } catch (IOException var5) {
            var5.printStackTrace();
        }

    }

    public static void saveFileUTF8(String path, String content, Boolean append) throws IOException {
        FileOutputStream fos = new FileOutputStream(path, append.booleanValue());
        OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");
        out.write(content);
        out.flush();
        out.close();
        fos.flush();
        fos.close();
    }

    public static String getFileUTF8(String path) {
        String result = "";
        FileInputStream fin = null;

        try {
            fin = new FileInputStream(path);
            int length = fin.available();
            byte[] buffer = new byte[length];
            fin.read(buffer);
            fin.close();
            result = new String(buffer, "UTF-8");
        } catch (Exception var5) {
            ;
        }

        return result;
    }

    public static Intent getFileIntent(String path, String mimeType) {
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.setDataAndType(Uri.fromFile(new File(path)), mimeType);
        return intent;
    }

    public static String getDiskCacheDir(Context context) {
        String cachePath = null;
        if(!"mounted".equals(Environment.getExternalStorageState()) && Environment.isExternalStorageRemovable()) {
            cachePath = context.getCacheDir().getPath();
        } else {
            cachePath = context.getExternalCacheDir().getPath();
        }

        return cachePath;
    }

    public static String getDiskFileDir(Context context) {
        String cachePath = null;
        if(!"mounted".equals(Environment.getExternalStorageState()) && Environment.isExternalStorageRemovable()) {
            cachePath = context.getFilesDir().getPath();
        } else {
            cachePath = context.getExternalFilesDir(Environment.DIRECTORY_MOVIES).getPath();
        }

        return cachePath;
    }

    public static void mergeFiles(Context context, File outFile, List<File> files) {
        FileChannel outChannel = null;

        try {
            outChannel = (new FileOutputStream(outFile)).getChannel();
            Iterator ioe = files.iterator();

            while(ioe.hasNext()) {
                File f = (File)ioe.next();
                FileChannel fc = (new FileInputStream(f)).getChannel();
                ByteBuffer bb = ByteBuffer.allocate(8192);

                while(fc.read(bb) != -1) {
                    bb.flip();
                    outChannel.write(bb);
                    bb.clear();
                }

                fc.close();
            }

            Log.d("RxFileTool", "拼接完成");
        } catch (IOException var16) {
            var16.printStackTrace();
        } finally {
            try {
                if(outChannel != null) {
                    outChannel.close();
                }
            } catch (IOException var15) {
                ;
            }

        }

    }

    public static String getNativeM3u(Context context, File file, List<File> pathList) {
        FileInputStream in = null;
        int num = 0;
        StringBuffer buf = new StringBuffer();

        try {
            if(file != null) {
                in = new FileInputStream(file);
            }

            BufferedReader e1 = new BufferedReader(new InputStreamReader(in));
            String line = "";

            while(true) {
                while((line = e1.readLine()) != null) {
                    if(line.length() > 0 && line.startsWith("http://")) {
                        buf.append("file:" + ((File)pathList.get(num)).getAbsolutePath() + "\r\n");
                        ++num;
                    } else {
                        buf.append(line + "\r\n");
                    }
                }

                in.close();
                write(file.getAbsolutePath(), buf.toString());
                Log.d("ts替换", "ts替换完成");
                break;
            }
        } catch (FileNotFoundException var8) {
            var8.printStackTrace();
        } catch (IOException var9) {
            var9.printStackTrace();
        }

        return buf.toString();
    }

    public static void write(String filePath, String content) {
        BufferedWriter bw = null;

        try {
            bw = new BufferedWriter(new FileWriter(filePath));
            bw.write(content);
        } catch (Exception var12) {
            var12.printStackTrace();
        } finally {
            if(bw != null) {
                try {
                    bw.close();
                } catch (IOException var11) {
                    bw = null;
                }
            }

        }

    }

    public static Vector<String> GetAllFileName(String fileAbsolutePath, String suffix) {
        Vector vecFile = new Vector();
        File file = new File(fileAbsolutePath);
        File[] subFile = file.listFiles();

        for(int iFileLength = 0; iFileLength < subFile.length; ++iFileLength) {
            if(!subFile[iFileLength].isDirectory()) {
                String filename = subFile[iFileLength].getName();
                if(filename.trim().toLowerCase().endsWith(suffix)) {
                    vecFile.add(filename);
                }
            }
        }

        return vecFile;
    }




    public static boolean isFileExists(File file) {
        return file != null && file.exists();
    }


    public static boolean isDir(File file) {
        return isFileExists(file) && file.isDirectory();
    }


    public static boolean isFile(File file) {
        return isFileExists(file) && file.isFile();
    }


    public static boolean createOrExistsDir(File file) {
        boolean var10000;
        label25: {
            if(file != null) {
                if(file.exists()) {
                    if(file.isDirectory()) {
                        break label25;
                    }
                } else if(file.mkdirs()) {
                    break label25;
                }
            }

            var10000 = false;
            return var10000;
        }

        var10000 = true;
        return var10000;
    }

    public static boolean createOrExistsFile(File file) {
        if(file == null) {
            return false;
        } else if(file.exists()) {
            return file.isFile();
        } else if(!createOrExistsDir(file.getParentFile())) {
            return false;
        } else {
            try {
                return file.createNewFile();
            } catch (IOException var2) {
                var2.printStackTrace();
                return false;
            }
        }
    }



    public static boolean createFileByDeleteOldFile(File file) {
        if(file == null) {
            return false;
        } else if(file.exists() && file.isFile() && !file.delete()) {
            return false;
        } else if(!createOrExistsDir(file.getParentFile())) {
            return false;
        } else {
            try {
                return file.createNewFile();
            } catch (IOException var2) {
                var2.printStackTrace();
                return false;
            }
        }
    }









    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = "_data";
        String[] projection = new String[]{column};

        String var8;
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, (String)null);
            if(cursor == null || !cursor.moveToFirst()) {
                return null;
            }

            int index = cursor.getColumnIndexOrThrow(column);
            var8 = cursor.getString(index);
        } finally {
            if(cursor != null) {
                cursor.close();
            }

        }

        return var8;
    }

    public static void closeIOQuietly(Closeable... closeables) {
        if(closeables != null) {
            Closeable[] var1 = closeables;
            int var2 = closeables.length;

            for(int var3 = 0; var3 < var2; ++var3) {
                Closeable closeable = var1[var3];
                if(closeable != null) {
                    try {
                        closeable.close();
                    } catch (IOException var6) {
                        ;
                    }
                }
            }

        }
    }

    public static String file2Base64(String filePath) {
        FileInputStream fis = null;
        String base64String = "";
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            fis = new FileInputStream(filePath);
            byte[] e = new byte[102400];
            boolean count = false;

            int count1;
            while((count1 = fis.read(e)) != -1) {
                bos.write(e, 0, count1);
            }

            fis.close();
        } catch (Exception var6) {
            var6.printStackTrace();
        }

        base64String = Base64.encodeToString(bos.toByteArray(), 0);
        return base64String;
    }

    public void TextToFile(String strFilePath, String strBuffer) {
        FileWriter fileWriter = null;

        try {
            File ex = new File(strFilePath);
            fileWriter = new FileWriter(ex);
            fileWriter.write(strBuffer);
        } catch (IOException var13) {
            var13.printStackTrace();
        } finally {
            try {
                fileWriter.flush();
                fileWriter.close();
            } catch (IOException var12) {
                var12.printStackTrace();
            }

        }

    }

    public void readFileByLines(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;

        try {
            System.out.println("以行为单位读取文件内容，一次读一整行：");
            reader = new BufferedReader(new FileReader(file));
            String e = null;

            for(int line = 1; (e = reader.readLine()) != null; ++line) {
                System.out.println("line?????????????????????????????????? " + line + ": " + e);
            }

            reader.close();
        } catch (IOException var15) {
            var15.printStackTrace();
        } finally {
            if(reader != null) {
                try {
                    reader.close();
                } catch (IOException var14) {
                    ;
                }
            }

        }

    }
}
